#!/usr/bin/env bash

downloadCommitHook (){
    echo "The local version needs to be updated, start downloading ..."
    rm $workdir/commit-msg-* >/dev/null 2>&1  
    download=`curl -o $workdir/$hook_name $1`
}

workdir=`cd $(dirname $0) ;pwd`
hook_name=""
get_hook_download_url=""
remote_version_url=""
remote_version=`curl -s --connect-timeout 5 $remote_version_url`
hook_download_url=`curl -s --connect-timeout 5 $get_hook_download_url`

if [ "$remote_version" == "" ]
then
    exit 0 
fi

unameOut="$(uname -s)"
case "${unameOut}" in
    Linux*)     machine=commit-hook-Linux-$remote_version;;
    Darwin*)    machine=commit-hook-Mac-$remote_version;;
    MINGW*)     machine=commit-hook-Win-$remote_version".exe";;
esac

if [ "$machine" == commit-hook-Win-$remote_version".exe" ]
then  
    hook_name="$machine"
    if [ ! -f "$workdir/$hook_name" ]; then
        downloadCommitHook "$hook_download_url/$hook_name"
    fi
else
    hook_name="$machine"
    if [ ! -f "$workdir/$hook_name" ]; then
        downloadCommitHook "$hook_download_url/$hook_name"
        chmod +x "$workdir/$hook_name"
    fi
fi

exec "$workdir/$hook_name"